from common.libs.member.MemberService import MemberService
from common.models.member import Member
from flask import request, g
from application import app
from flask import jsonify
import re

@app.before_request
def before_request():
    """拦截器"""

    res = {'code': -1, 'msg': '请先登入！', 'data': {}}
    ignore_check_urls = app.config['API_IGNORE_URLS']
    path = request.path

    if '/api' not in path:
        return None

    # 执行登录校验
    member = member_check_login()
    g.current_member = None
    if member:
        g.current_member = member
        return None

    pattern = re.compile('|'.join(ignore_check_urls))
    if pattern.match(path):
        return None

    if not member:
        return jsonify(res)


def member_check_login():
    """登录校验"""
    auth_token_info = request.headers.get('Authorization')
    if not auth_token_info:
        return False
    member_info = auth_token_info.split('#')
    if len(member_info) != 2:
        return False
    try:
        member = Member.query.filter_by(id=member_info[1]).first()
    except Exception:
        return False
    else:
        if member.status == 0:
            return False

    if MemberService.geneAuthCode(member) != member_info[0]:
        return False
    return member
